<?php
namespace app\api\controller\v1;
use think\Db;
use app\service\UserWeixinService;
use app\service\TechnWeixinService;
use app\service\PosterService;
use app\service\TechnService;

use app\service\PaymentService;



class Index extends Base
{
	public function _initialize()
	{
		parent::_initialize();
	}

	/**
	 * 获取轮播图片
	 */
	public function get_slide()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$map = [
			'is_delete_time' => 0
		];
		$list_data = Db::name('slide')->where($map)->order('sort asc')->select();
		if(!empty($list_data))
		{
			//遍历处理
			foreach($list_data as $key => $value)
			{
				//图片
				$list_data[$key]['images_url'] = request()->domain().$value['images_url'];
			}

            $user = $this->user;
            if (!empty($user)){
                $result['data']['login'] = 2;
            }else{
                $result['data']['login'] = 1;
            }
			$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data']['list'] = $list_data;

		}else
		{
            if (!empty($user)){
                $result['data']['login'] = 2;
            }else{
                $result['data']['login'] = 1;
            }
			$result['code'] = -1;
	        $result['msg'] = "暂无数据";
		}
		echo json_encode($result);
	}
	
	
	
	
	
	
	
	//计算技师等级
	public function TechnLevelUpgrade(){
	    
	    $list=db::name('techn')->field('id,province,city')->select();
	    foreach ($list as $k=>$v){
	        
	        $proxy_id=db::name('proxy')->where(['sheng'=>$v['province'],'shi'=>$v['city'],'type'=>2])->value('proxy_id');
	        
	        if(empty($proxy_id)){
	            $proxy_id=0;
	        }
	        
	        $amount=db::name('order')->where(['techn_id'=>$v['id'],'status'=>['notin','0,7']])->sum('price');
	        
	        $rank=Db::name('techn_level')->where(['proxy_id' => $proxy_id,'low_result'=>['<=',$amount]])->order('rank','asc')->limit(1)->value('rank');
	        
	        db::name('techn_last')->where('techn_id',$v['id'])->update(['divide_rank'=>$rank,'nature_rank'=>$rank]);
	        
	    }
	}
	
	
	
	
	
	
	//分享二维码
    public function get_code(PosterService $posterService){
        
		$params = $this->data_post;
		
        $user_token = $params['user_token'];
        
        $uid=db::name('user_token')->where('token',$user_token)->value('user_id');
        
        include_once EXTEND_PATH . 'phpqrcode/phpqrcode.php';
        //查找分销设置信息
        $url = request()->domain(). '/h5/pages/index/index?uid='.$uid;
        
        // $poster_data=$poster->where('id',$set_data['poster_id'])->find();
        $level = 3;
        $size = 4;
        $errorCorrectionLevel = intval($level); //容错级别
        $matrixPointSize = intval($size); //生成图片大小
        $path = ROOT_PATH.'public'.DS.'static/wechat'.'/';
        $fileName = 'qrcode_'.$uid.'.png';
        
        $local_path = request()->domain().DS.'public/static/wechat/';
        if (!file_exists($local_path)) {
            if (!file_exists($path)) {
                mkdir($path);
            }
            //生成二维码
            \QRcode::png($url, $path . $fileName, $errorCorrectionLevel, $matrixPointSize);
            
        }
        
        $result['code'] = 0;
        $result['msg'] = "请求成功";
        $result['data'] = request()->domain().DS.'static/wechat/'.$fileName;
        
		echo json_encode($result);
    }
	
	
// 	https://www.hexukeji.com/virtual/CallBack/aliyunCallBack
	public function aliyuncallback(){
	    
		$params = $this->data_post;
		file_put_contents('aliyuncallback.txt',json_encode($params)."\n",FILE_APPEND);
		
        $result['code'] = 0;
        $result['msg'] = "成功";
        
		echo json_encode($result);
		
	}
	//推送测试
	public function ce(){
	    
	    $order_info=db::name('order')->where('id',3330)->find();
	    
	    $openid = Db::name('user_weixin')->where(['user_id' => $order_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
	    
	    $order_detail_title = Db::name('order_detail')->where(['order_id' => $order_info['id']])->column('title');
	       // $order_detail_title = implode(',', $order_detail_title);
	        $order_detail_title_new='服务项目:'.implode(',',$order_detail_title);
		      //  foreach ($order_detail_title as $k=>$v){
		      //      $order_detail_title_new.="\n ".($k+1).'.'.$v;
		      //  }
		        
	        $tem_msg['touser'] = $openid;
	        $tem_msg['template_id'] = '0AKe-kYOFFklpG22aP1oiAIS76v8pIh5_xBNbGbZUck';
	        $tem_msg['url'] = request()->domain().'/h5/pages/order/orderdetail?order_id='.$order_info['id'];
	        $tem_msg['data'] = [
	            'first' => [
	                'value' => '技师已接受您的订单，技师将会尽快与您取得联系，请保持手机畅通',
	                'color' => '#173177'
	            ],
	            'keyword1' => [
	                'value' => $order_info['order_no'],
	                'color' => '#173177'
	            ],
	            'keyword2' => [
	                'value' => $order_detail_title_new,
	                'color' => '#173177'
	            ],
	            'keyword3' => [
	                'value' => '111',
	                'color' => '#173177'
	            ],
	            'remark' => [
	                'value' => '感谢您的使用！',
	                'color' => '#173177'
	            ]
	        ];
	        UserWeixinService::send_wx_web_tem_msg($tem_msg);
	}
	
	public function ce2(){
	    
	    $queues_data['id']=2956;
	    
	    $order_info = Db::name('order')->where(['id' => $queues_data['id']])->find();
	    
	    $openid = Db::name('user_weixin')->where(['user_id' => $order_info['user_id'],'identity_type'=>'user'])->value('openid');
        $tem_msg['touser'] = $openid;
        $tem_msg['template_id'] = 'i1sheff0vHc8p1iqiHqNJe1N0drRP7l_UYK53dJsYJA';
		$tem_msg['url'] = request()->domain().'/h5/pages/order/orderdetail?order_id='.$queues_data['id'];
		
        $tem_msg['data'] = [
            'first' => [
                'value' => '服务结束提醒',
                'color' => '#173177'
            ],
            'keyword1' => [
                'value' => $order_info['order_no'],
                'color' => '#173177'
            ],
            'keyword2' => [
                'value' => date('Y-m-d H:i:s',$order_info['pre_start_time']),
                'color' => '#173177'
            ],
            'keyword3' => [
                'value' => date('Y-m-d H:i:s',$order_info['pre_end_time']),
                'color' => '#173177'
            ],
            'keyword4' => [
                'value' => '正常',
                'color' => '#173177'
            ],
            'remark' => [
                'value' => '感谢使用，欢迎再次使用',
                'color' => '#173177'
            ]
        ];
		$a=UserWeixinService::send_wx_web_tem_msg($tem_msg);
		print_r($a);
	}
	
	public static function zfOrderPayHandle()
	{
	    $params['order']=db::name('order')->where('id','1865')->find();
	    $params['payment']['payment']='Weixin';
	    $params['payment']['name']='微信';
	    
	   team_get(973);
	   exit;
		//写入结算数据
		$balance_data = [];
		//结算剩余百分比
		$balance_surplus_scale = 100;
		//服务剩余费用
		$balance_surplus_price = $params['order']['price'];
		//查询技师等级写入结算数据
		
		//渠道费
		$preferential_price=0;
		
		//查询技师信息
		$techn_info = Db::name('techn')->where(['id' => $params['order']['techn_id']])->find();
		
		team_get($techn_info['user_id']);
		team_get($params['order']['user_id']);
		
		//用户分佣
		if($params['order']['poster_id']>0 && $params['order']['poster_id']!=$params['order']['user_id']){
		    $user=db::name('user')->where('id',$params['order']['poster_id'])->find();
		        $daytime=strtotime(date('Y-m-d'));
		        $add_time=$user['add_time'];
		        $bl=$user['share_bl'];
		        
		        $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
    		    if($bl>0){
    		        $balance_data[] = [
    				'balance_type' => 3,
    				'order_id' => $params['order']['id'],
    				'identity_type' => 'user',
    				'identity_id' => $params['order']['poster_id'],
    				'divide_into' => $bl/100,
    				'price' => $params['order']['price']-$params['order']['preferential_price'],
    				'no_money' => $no_money,
    				'msg' => '用户分佣',
    				'add_time' => time(),
    				'upd_time' => time(),
    				'khtype'=>1
    			];
    			$preferential_price+=$no_money;
		    }
		}
		
		
		
// 		//上级返利
        $userupid=db::name('user_bd')->where('bduid',$techn_info['user_id'])->value('user_id');
        
		if(!empty($userupid)){
		    
		    //上级用户
		    $user=db::name('user')->where('id',$userupid)->find();
		    
		    $techn_up=Db::name('techn')->where('user_id',$userupid)->find();
		    
		    $user_bd=db::name('user_bd')->where(['user_id'=>$userupid,'bduid'=>$techn_info['user_id']])->find();
		    
		    
		    if(!empty($techn_up)){//技师推技师
		        $bl=$user_bd['bd_bl2'];
		    }else{//技师推用户
		        $bl=$user_bd['bd_bl'];
		    }
		    
		    print_r($bl);
	        $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
		    if($bl>0&&$no_money>0){
		        $balance_data[] = [
    				'balance_type' => 4,
    				'order_id' => $params['order']['id'],
    				'identity_type' => 'user',
    				'identity_id' => $userupid,
    				'divide_into' => $bl/100,
    				'price' => $params['order']['price']-$params['order']['preferential_price'],
    				'no_money' => $no_money,
    				'msg' => '技师分佣',
    				'add_time' => time(),
    				'upd_time' => time(),
    				'khtype'=>2
    			];
    			
    			$preferential_price+=$no_money;
		    }
		}
		
		exit;
		//用户-》技师
		$userinfo=db::name('user')->where('id',$params['order']['user_id'])->find();
		if(!empty($userinfo['upid'])){
		    
		    $user_bd=db::name('user_bd')->where(['user_id'=>$userinfo['upid'],'bduid'=>$userinfo['id']])->find();
		    
		    $bl=$user_bd['bd_bl3'];
		    
	        $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
		    if($bl>0&&$no_money>0){
		        $balance_data[] = [
    				'balance_type' => 4,
    				'order_id' => $params['order']['id'],
    				'identity_type' => 'user',
    				'identity_id' => $userinfo['upid'],
    				'divide_into' => $bl/100,
    				'price' => $params['order']['price']-$params['order']['preferential_price'],
    				'no_money' => $no_money,
    				'msg' => '技师分佣',
    				'add_time' => time(),
    				'upd_time' => time(),
    				'khtype'=>2
    			];
    			
    			$preferential_price+=$no_money;
		    }
		}
		
		
		
		//查询技师实时数据
		$techn_last_info = Db::name('techn_last')->where(['techn_id' => $params['order']['techn_id']])->find();
		
		if(!empty($techn_last_info))
		{
		    if(!empty($techn_last_info['divide_into'])){
		        //技师分成比例
				$techn_divide_into = $techn_last_info['divide_into'];
				//技师分成金额
				$techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($params['order']['price']-$preferential_price-$params['order']['preferential_price']));
				//技师服务费用结算数据
				$techn_service_data = [
					'balance_type' => 1,
					'order_id' => $params['order']['id'],
					'identity_type' => 'techn',
					'identity_id' => $params['order']['techn_id'],
					'divide_into' => $techn_divide_into,
					'price' => $params['order']['price'],
					'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
					'msg' => '技师分成',
					'add_time' => time(),
					'upd_time' => time(),
    				'khtype'=>2
				];
				$balance_surplus_scale -= $techn_service_data['divide_into'];
				$balance_surplus_price -= $techn_service_data['no_money'];
				$balance_data[] = $techn_service_data;
		    }else{
		        //如果技师实时信息存在查询对应等级
    			//检查等级条件
    			$techn_level_map = [
    				'is_delete_time' => 0,
    				'rank' => $techn_last_info['divide_rank'],
    				'proxy_id'=>0
    			];
    			$techn_level_info = Db::name('techn_level')->where($techn_level_map)->find();
    			if(!empty($techn_level_info))
    			{
    				//如果技师等级存在
    				//结算服务分成
    				if($balance_surplus_price >= 0.01)
    				{
    					//技师分成比例
    					$techn_divide_into = $techn_level_info['divide_into'];
    					//技师分成金额
    					$techn_no_money = PriceNumberFormat(($techn_divide_into/100)*$params['order']['price']);
    					//技师服务费用结算数据
    					$techn_service_data = [
    						'balance_type' => 1,
    						'order_id' => $params['order']['id'],
    						'identity_type' => 'techn',
    						'identity_id' => $params['order']['techn_id'],
    						'divide_into' => $techn_divide_into,
    						'price' => $params['order']['price'],
    						'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
    						'msg' => '技师分成',
    						'add_time' => time(),
    						'upd_time' => time(),
    				        'khtype'=>2
    					];
    					$balance_surplus_scale -= $techn_service_data['divide_into'];
    					$balance_surplus_price -= $techn_service_data['no_money'];
    					$balance_data[] = $techn_service_data;
    				}
    			}
    		}
	    }
		
		//技师出行费用结算数据
		$balance_data[] = [
			'balance_type' => 2,
			'order_id' => $params['order']['id'],
			'identity_type' => 'techn',
			'identity_id' => $params['order']['techn_id'],
			'divide_into' => 100,
			'price' => $params['order']['travel_price'],
			'no_money' => $params['order']['travel_price'],
			'msg' => '技师出行',
			'add_time' => time(),
			'upd_time' => time(),
			'khtype'=>2
		];
		
		
		
		//查看机构结算数据
		$proxy_info = Db::name('proxy')->where(['shi' => $techn_info['city'], 'commission' => ['GT', 0]])->find();
		if(!empty($proxy_info))
		{
			if($balance_surplus_price >= 0.01)
			{
				//机构分成比例
				$proxy_commission = 100-$proxy_info['commission']-$techn_divide_into;
				//机构分成金额
				$proxy_no_money = PriceNumberFormat(($proxy_commission/100)*$params['order']['price']);
				//机构结算数据
				$proxy_service_data = [
					'balance_type' => 1,
					'order_id' => $params['order']['id'],
					'identity_type' => 'proxy',
					'identity_id' => $proxy_info['proxy_id'],
					'divide_into' => $proxy_commission,
					'price' => $params['order']['price'],
					'no_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
					'msg' => '机构分成',
					'add_time' => time(),
					'upd_time' => time(),
    				'khtype'=>2
				];
				$balance_surplus_scale -= $proxy_service_data['divide_into'];
				$balance_surplus_price -= $proxy_service_data['no_money'];
				$balance_data[] = $proxy_service_data;
			}
		}
		//系统平台结算数据
		if($balance_surplus_price >= 0.01)
		{
			$balance_data[] = [
				'balance_type' => 1,
				'order_id' => $params['order']['id'],
				'identity_type' => 'system',
				'identity_id' => 0,
				'divide_into' => $balance_surplus_scale,
				'price' => $params['order']['price'],
				'no_money' => $balance_surplus_price,
				'msg' => '平台分成',
				'add_time' => time(),
				'upd_time' => time(),
				'khtype'=>2
			];
		}
		
// 		
		
		
		
		if(!empty($balance_data))
		{
			$balance_count = Db::name('balance')->insertAll($balance_data);
			if($balance_count <= 0)
			{
				Db::rollback();
			    return ['code' => -1, 'msg' => '结算数据添加失败'];
			}
		}
		//提交事务
		Db::commit();
		
		return 7;
	}
	
	
	public static $status_array = [
		0 => ['value' => 0, 'name' => '待支付'],
		1 => ['value' => 1, 'name' => '待接单'],
		2 => ['value' => 2, 'name' => '已接单'],
		3 => ['value' => 3, 'name' => '已出发'],
		4 => ['value' => 4, 'name' => '已到达'],
		5 => ['value' => 5, 'name' => '开始服务'],
		6 => ['value' => 6, 'name' => '已完成'],
		7 => ['value' => 7, 'name' => '已取消'],
		8 => ['value' => 8, 'name' => '已关闭'],
	];
	
	
	
	
	public function upgrade_pay()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = db::name('user')->where('id','1264')->find();
		$params['order_id']=3;
		
        //查询订单信息
        $order_info = Db::name('order_upgrade')->where(['id' => $params['order_id']])->find();
        
        $order=db::name('order')->where('id',$order_info['order_id'])->find();
        
		$pre_end_time=$order['pre_end_time'];
		
		
		if($order['status']!=5){
		    echo json_encode(['code' => -1, 'msg' => '本次订单已不可操作']);
			exit();
		}
		
        // 支付方式
        $payment_array = PaymentService::$payment_array;
        $payment = $payment_array[$order_info['payment_id']];
        if(empty($payment))
        {
        	echo json_encode(['code' => -1, 'msg' => '支付方式有误']);
			exit();
        }
        
        //支付参数
        $pay_data = [
        	'user' => $params['user'],
        	'order_id' => $order_info['id'],
        	'order_no' => $order_info['order_no'],
        	'name' => '订单支付',
        	'total_price' => $order_info['price'],
        	'client_type' => 'h5',
        	'notify_url' => request()->domain().'/api/v1/ordernotify/'.strtolower($payment['uppayment']),
        	'call_back_url' => request()->domain().'/h5/pages/order/order',
        	'redirect_url' => '',
        	'site_name' => '摩小妹',
        	'ajax_url' => '',
        ];
        
        
        
        // 发起支付
        $pay_name = 'payment\\'.$payment['uppayment'];
        if($order_info['payment_id']==1){
            $pay_name = 'payment\Weixin';
        }
        $ret = (new $pay_name($payment['config']['user']))->Pay($pay_data);
        if(isset($ret['code']) && $ret['code'] == 0)
        {
        	$result = $ret;
        }else
        {
        	$result['code'] = -100;
        	$result['msg'] = empty($ret['msg']) ? '支付接口异常' : $ret['msg'];
        }
        echo json_encode($result);
	}
	
	
	
	public function gzces(){
	    
	    $text=file_get_contents(request()->domain().'/api/v1/webview/jyxy');
	   
	    print_r($text);
	}
    
    
    public function tuis(){
        
        //创建任务： 项目命名空间\模块\文件夹\控制器@方法
    // 		$job = "app\service\QueuesService@ivrCall";
    // 		//延时时间
    // 		$delayed_second = 5;
    // 		$queues_data = ['mobile' => '15235175363'];
    // 		\think\Queue::later($delayed_second, $job, $queues_data, 'ivrCall');
    		ivrCall('LTAI5tCfyuqK4o58i6MH3qH2', 'xXOnPRM4tMimqDVR4e1Ms5crn0lUtP', '057156104394', '15235175363', 'TTS_269350009');
    }
    
    
    public function get_jsApi_ticket()
    {
        print_r(11111111);
    }
    
    
}